package com.company.project.controller;
import com.google.common.collect.Lists;
import java.util.Date;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.company.project.common.aop.annotation.DataScope;
import com.company.project.common.utils.DataResult;
import com.company.project.entity.CostEntity;
import com.company.project.entity.SysCompleteEntity;
import com.company.project.entity.SysOrderEntity;
import com.company.project.service.SysCompleteService;
import com.company.project.service.SysCostService;
import com.company.project.service.SysOrderService;
import com.company.project.util.ExcelUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 订单管理
 *
 * @author Jake
 * @version V1.0
 */
@Slf4j
@Api(tags = "订单管理")
@RestController
@RequestMapping("/sysComplete")
public class SysCompleteController {
    @Resource
    private SysCompleteService sysCompleteService;

    @Resource
    private SysCostService sysCostService;

    @Resource
    private SysOrderService sysOrderService;

    @ApiOperation(value = "新增")
    @PostMapping("/add")
    @RequiresPermissions("sysComplete:add")
    public DataResult add(@RequestBody SysCompleteEntity sysComplete) {
        sysCompleteService.save(sysComplete);
        return DataResult.success();
    }


    @ApiOperation(value = "上传excel")
    @PostMapping("/import")
    @RequiresPermissions(value = {"sysComplete:add", "sysContent:add"}, logical = Logical.OR)
    public DataResult importFile(@RequestPart(value = "file") MultipartFile file) {
        try {
            String fileName = file.getOriginalFilename();
            InputStream inputStream = file.getInputStream();
            Map<String, String> map = new HashMap<>();
            map.put("BIP", "bip");
            map.put("SKU", "sku");
            map.put("商品名称", "cName");
            map.put("送货数量", "cNumber");
            map.put("送货日期", "cTime");
            map.put("仓库名称", "warehouse");
            map.put("订单状态", "cStatus");
            map.put("入库时间", "createTime");
            map.put("实际销售价", "realPirce");
            map.put("UPC", "upc");
            map.put("品牌名", "brandName");

            List<SysCompleteEntity> list = ExcelUtil.excelToList(fileName , inputStream, SysCompleteEntity.class, map, "yyyy-MM-dd HH:mm:ss");
            List<CostEntity> costEntities = Lists.newArrayList();


            for (SysCompleteEntity entity : list) {
                sysCompleteService.save(entity);

                String entityBIP = entity.getBip();
                String entitySku = entity.getSku();
                String unityID = entityBIP + entitySku;
                log.debug("入库单的唯一ID 是：" +unityID);

                List<SysOrderEntity> orderEntityList = sysOrderService.list();
                for (SysOrderEntity orderEntity : orderEntityList) {
                    String orderBip = orderEntity.getPurchaseId();
                    String orderId = orderEntity.getOrderId();
                    String orderInfo = orderBip + orderId;
                    log.debug("采购单的唯一ID 是：" +orderInfo);
                    if (unityID.equals(orderInfo)) {
                        log.debug("发现共同ID 确定唯一订单：" +orderInfo);
                        // 实际销售价
                        double realSalePrice = entity.getRealPirce();
                        // 成本价：实际销售价*0.925
                        double costPrice = realSalePrice * 0.925;
                        // 毛利润 : 销售总金额-采购总金额
                        double grossProfit = orderEntity.getETotalPrice() - costPrice * entity.getCNumber();
                        // 毛利率 : 毛利润/销售总金额
                        double grossMargin = grossProfit / orderEntity.getETotalPrice();
                        // 预留广告费金额 ； （销售价格-实际销售价格）*数量
                        double adPrice = (orderEntity.getEPrice() - realSalePrice) * costPrice * entity.getCNumber();

                        CostEntity cost = new CostEntity();
                        cost.setBrand(entity.getBrandName());
                        cost.setUpc(entity.getUpc());
                        cost.setSku(entity.getSku());
                        cost.setProductName(entity.getCName());
                        cost.setPurchasePrice(entity.getRealPirce() * 0.925);
                        cost.setProductNumber(orderEntity.getENumber());
                        cost.setPurchaseTotalPrice(entity.getRealPirce() * 0.925 * orderEntity.getENumber());
                        cost.setSalePrice(orderEntity.getEPrice());
                        cost.setSaleNumber(entity.getCNumber());
                        cost.setSaleTotalPrice(orderEntity.getEPrice() * entity.getCNumber());
                        cost.setGrossProfit(grossProfit);
                        cost.setGrossMargin(grossMargin);
                        cost.setBip(entity.getBip());
                        cost.setRealSalePrice(realSalePrice);
                        cost.setAdPrice(adPrice);
                        cost.setJdPerson(orderEntity.getJdPerson());
                        cost.setCreateTime(new Date());
                        sysCostService.save(cost);
                        costEntities.add(cost);
                    }
                }
            }
            //计算本次的广告费
            sysCostService.calculateAdCost(costEntities);
           log.info("importFile:{}",list);
        } catch (Exception e) {
            log.info("importFile error. {}",e);
            return DataResult.fail("上传失败...");
        }
        return DataResult.success();
    }

    @ApiOperation(value = "删除")
    @DeleteMapping("/delete")
    @RequiresPermissions("sysComplete:delete")
    public DataResult delete(@RequestBody @ApiParam(value = "id集合") List<String> ids) {
        sysCompleteService.removeByIds(ids);
        return DataResult.success();
    }

    @ApiOperation(value = "更新")
    @PutMapping("/update")
    @RequiresPermissions("sysComplete:update")
    public DataResult update(@RequestBody SysCompleteEntity sysComplete) {
        sysCompleteService.updateById(sysComplete);
        return DataResult.success();
    }

    @ApiOperation(value = "查询分页数据")
    @PostMapping("/listByPage")
    @RequiresPermissions("sysComplete:list")
    @DataScope
    public DataResult findListByPage(@RequestBody SysCompleteEntity sysComplete) {
        System.out.println("[findListByPage] , findListByPage.....sysComplete"+sysComplete);
        Page page = new Page(sysComplete.getPage(), sysComplete.getLimit());
        LambdaQueryWrapper<SysCompleteEntity> queryWrapper = Wrappers.lambdaQuery();
//        //查询条件示例
//        if (!StringUtils.isEmpty(sysComplete.getE_name())) {
//            queryWrapper.like(sysCompleteEntity::getE_name, sysComplete.getE_name());
//        }
//
        IPage<SysCompleteEntity> iPage = sysCompleteService.page(page, queryWrapper);
        List<SysCompleteEntity> list = iPage.getRecords();

        return DataResult.success(iPage);
    }
}
